<template>
  <el-dialog
    title="添加小程序商品"
    :modal-append-to-body="false"
    :before-close="closeFunc"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="500px"
  >
    <el-form
      size="small"
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="商品名称" prop="name"
        ><el-input v-model="ruleForm.name"></el-input
      ></el-form-item>

      <el-form-item
        label="商品封面图"
        prop="coverImgId"
        :rules="[{ required: true, message: '请上传商品封面图' }]"
      >
        <div>
          <el-button type="primary" @click="openUpload('cover')"
            >上传图片</el-button
          >
          <img
            :src="coverImgPath"
            class="mt10"
            :width="120"
            v-if="ruleForm.coverImgId != ''"
          />
          <div class="gray9">建议尺寸300*300,大小不超过2M</div>
          <!--上传图片组件-->
          <Upload
            v-if="isupload"
            :isupload="isupload"
            @returnImgs="returnImgsFunc"
            >上传图片</Upload
          >
        </div>
      </el-form-item>

      <el-form-item label="价格类型" prop="type">
        <el-radio-group v-model="ruleForm.priceType">
          <el-radio :label="1">一口价</el-radio>
          <el-radio :label="2">价格区间</el-radio>
          <el-radio :label="3">折扣价</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="价格："
        prop="price"
        :rules="[
          { required: true, message: '请输入最低价格', trigger: 'change' },
        ]"
        v-if="ruleForm.priceType == 1"
      >
        <el-input
          type="text"
          min="0"
          v-model="ruleForm.price"
          class="mb16 max-w460"
          placeholder="请输入价格"
        ></el-input>
      </el-form-item>

      <el-form-item
        label="价格："
        prop="price"
        :rules="[
          { required: true, message: '请输入最低价格', trigger: 'change' },
        ]"
        v-if="ruleForm.priceType == 2"
      >
        <el-input
          type="text"
          min="0"
          v-model="ruleForm.price"
          class="mb16 max-w460"
          placeholder="请输入最低价格"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="价格："
        prop="price2"
        :rules="[
          { required: true, message: '请输入最高价格', trigger: 'change' },
        ]"
        v-if="ruleForm.priceType == 2"
      >
        <el-input
          type="text"
          min="0"
          v-model="ruleForm.price2"
          class="mb16 max-w460"
          placeholder="请输入最高价格"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="price"
        :rules="[{ required: true, message: '请输入原价', trigger: 'change' }]"
        label="价格："
        v-if="ruleForm.priceType == 3"
      >
        <el-input
          type="text"
          min="0"
          v-model="ruleForm.price"
          class="mb16 max-w460"
          placeholder="请输入原价"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="price2"
        :rules="[{ required: true, message: '请输入现价', trigger: 'change' }]"
        label="价格："
        v-if="ruleForm.priceType == 3"
      >
        <el-input
          type="text"
          min="0"
          v-model="ruleForm.price2"
          class="mb16 max-w460"
          placeholder="请输入现价"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="productId"
        :rules="[{ required: true, message: '请绑定商品' }]"
        ><el-button @click="openProduct()">绑定商品</el-button></el-form-item
      >
      <el-form-item v-if="ruleForm.productId != ''">{{
        productName
      }}</el-form-item>
      <el-form-item
        ><img
          :src="productImgPath"
          class="mt10"
          :width="120"
          v-if="ruleForm.productImgId != ''"
      /></el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" @click="closeFunc()">取 消</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          :loading="loading"
          >立即提交</el-button
        >
      </div>
    </template>
    <!--商品选择-->
    <Product
      :isProduct="isproduct"
      :excludeIds="exclude_ids"
      :islist="false"
      @closeDialog="closeProductFunc"
    ></Product>
  </el-dialog>
</template>

<script>
import LiveApi from "@/api/live.js";
import Upload from "@/components/file/Upload.vue";
import Product from "@/components/product/Product.vue";

export default {
  components: {
    /*图片上传*/
    Upload: Upload,
    /*选择商品*/
    Product: Product,
  },

  data() {
    return {
      /*是否上传图片*/
      isupload: false,

      coverImgPath: "",
      shareImgPath: "",
      feedsImgPath: "",
      productImgPath: "",
      productName: "",
      ruleForm: {
        name: "",
        coverImgId: "",
        priceType: 1,
        price: "",
        price2: "",
        productId: "",
      },

      rules: {
        name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 3,
            max: 17,
            message: "长度在 3 到 17 个字符",
            trigger: "blur",
          },
        ],
        price: [{ required: true, message: "请输入价格", trigger: "change" }],
      },

      /*是否加载完成*/
      loading: false,

      /*是否打开选择商品*/
      isproduct: false,
      /*已有的id*/
      exclude_ids: [],
      imageType: "",
      /*左边长度*/
      formLabelWidth: "120px",
      /*是否显示*/
      dialogVisible: false,
    };
  },

  props: ["open", "productId", "type"],
  watch: {
    open: function (n, o) {
      if (n != o) {
        this.dialogVisible = n;
        console.log(n);
        console.log(this.type);
        if (n) {
          if (this.type == "edit") {
            this.getData();
          }
        }
      }
    },
  },

  created() {
    console.log(this.type);
  },

  methods: {
    closeFunc() {
      this.$emit("close");
    },

    getData() {
      LiveApi.toEditProduct({ productId: this.productId }).then((res) => {
        this.ruleForm = res.data;
        this.coverImgPath = res.data.coverImgPath;
        this.coverImgId = res.data.coverImgId;
        this.productId = res.data.productId;
        this.productImgPath = res.data.productImgPath;
      });
    },

    submitForm(formName) {
      let self = this;
      console.log(self.type);
      self.loading = true;
      if (self.type == "add") {
        self.$refs[formName].validate((valid) => {
          if (valid) {
            let param = self.ruleForm;
            LiveApi.addProduct(param)
              .then((data) => {
                self.loading = false;
                ElMessage({
                  message: "创建成功",
                  type: "success",
                });
                this.dialogVisible = false;
              })
              .catch((error) => {
                elf.loading = false;
              });
          } else {
            self.loading = false;
            return false;
          }
        });
      } else {
        self.$refs[formName].validate((valid) => {
          if (valid) {
            let param = self.ruleForm;
            LiveApi.editProduct(param)
              .then((data) => {
                self.loading = false;
                ElMessage({
                  message: "编辑成功",
                  type: "success",
                });
                this.dialogVisible = false;
              })
              .catch((error) => {
                elf.loading = false;
              });
          } else {
            self.loading = false;
            return false;
          }
        });
      }
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    /*上传*/
    openUpload(e) {
      this.imageType = e;
      this.isupload = true;
    },

    /*关闭商品选择*/
    closeProductFunc(e) {
      if (e.type == "success") {
        this.ruleForm.productId = e.params.productId;
        this.productImgPath = e.params.imagePath;
        this.productName = e.params.productName;
      }
      this.isproduct = false;
    },

    /*关闭弹窗*/
    cancelFunc(e) {
      this.$emit("close", {
        type: "error",
      });
    },

    /*打开添加*/
    openProduct() {
      this.isproduct = true;
    },

    /*上传图片*/
    uploadFile(fileId) {
      let self = this;
      const loading = ElLoading.service({
        lock: true,
        text: "文件上传中,请等待",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      LiveApi.uploadFile({ fileId }, (err) => {
        loading.close();
      })
        .then((response) => {
          loading.close();
          ElMessage({
            message: "上传文件成功",
            type: "success",
          });
        })
        .catch((response) => {
          loading.close();
        });
    },

    /*获取图片*/
    returnImgsFunc(e) {
      if (e != null && e.length > 0) {
        this.coverImgPath = e[0].filePath;
        this.ruleForm.coverImgId = e[0].fileId;
        this.uploadFile(this.ruleForm.coverImgId);
      }
      this.isupload = false;
    },
  },
};
</script>

<style scoped>
.img {
  margin-top: 10px;
}
</style>
